package com.zzyl.serve.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.CheckInApplyDto;
import com.zzyl.serve.dto.CheckInElderDto;
import com.zzyl.serve.dto.ElderFamilyDto;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.vo.CheckInConfigVo;
import com.zzyl.serve.vo.CheckInDetailVo;
import com.zzyl.serve.vo.CheckInElderVo;
import com.zzyl.serve.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author chenyang
 * @date 2025-08-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //1.如果老人已经入住（老人身份证已存在，且状态为1），则抛异常
        LambdaQueryWrapper<Elder> wrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());

        Elder elder = elderMapper.selectOne(wrapper);
        if (elder!=null && Objects.equals(elder.getStatus(),1)){
             throw new BaseException(("老人已入住"));
        }

        //2.更新该床位为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        if (Objects.equals(bed.getBedStatus(),1)){
            throw new BaseException("床位已入驻");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.保存老人信息，拿到老人信息，得到老人对象


        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elder1 = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder1);
        elder1.setStatus(1);
        elder1.setBedId(bed.getId());
        elder1.setBedNumber(bed.getBedNumber());
        List<ElderFamilyDto> familyDtoList = dto.getElderFamilyDtoList();
        elder1.setRemark(JSONUtil.toJsonStr(familyDtoList));
        if (elder == null){
            elderMapper.insertElder(elder1);
        }else{
            elder1.setId(elder.getId());
            elderMapper.updateById(elder1);
        }


        //新增入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder1.getName());
        checkIn.setElderId(elder1.getId());
        checkIn.setIdCardNo(dto.getCheckInElderDto().getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        save(checkIn);


        //新增入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);



        //新增签约信息
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder1.getId());
        contract.setElderName(elder1.getName());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        LocalDateTime now = LocalDateTime.now();
        boolean b = !now.isBefore(contract.getStartDate()) && !now.isAfter(contract.getEndDate());
        contract.setStatus(b?1:0);
        contractMapper.insert(contract);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo getCheckInDetail(Long id) {
        //组装CheckInDetailVo
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //1.组装老人入住表，checkInElderVo
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectElderById(id);

        BeanUtils.copyProperties(elder,checkInElderVo);
        String birthday = checkInElderVo.getBirthday();

        // 转换字符串为 LocalDate
        LocalDate birthDate = LocalDate.parse(checkInElderVo.getBirthday(), DATE_FORMATTER);

        // 计算年龄（精确到年）
        int age = Period.between(birthDate, LocalDate.now()).getYears();
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //组装老人家庭成员表

        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();

        String remark = elderMapper.getFamily(id);
        List<ElderFamilyVo> list = JSONUtil.toList(remark, ElderFamilyVo.class);

        elderFamilyVoList = list;

        //System.out.println("elderFamilyVoList = " + elderFamilyVoList);


        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);


        //组装checkInConfigVo
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInConfig checkInConfig =new CheckInConfig();
         checkInConfig =checkInConfigMapper.getCheckInConfig(id);


        System.out.println("checkInConfigVo = " + checkInConfig);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
         checkInDetailVo.setCheckInConfigVo(checkInConfigVo);





         //组装contract
        Contract contract = contractMapper.selectContractByElderId(id);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }


}
